import {Button, Col, Row} from "antd";
import {ModalForm, ProFormSelect, ProFormText} from "@ant-design/pro-components";
import {DiffOutlined, EditOutlined} from "@ant-design/icons";
import React from "react";
import {API} from "@/services/typings";
import {useModel} from "@@/exports";

interface IRoleEdit {
  isAdd: boolean;
  user?: API.CurrentUser;
  triggerButton?: React.ReactElement;
  onSubmit: (values: API.CurrentUser) => Promise<boolean>;
}

const UserEditModel: React.FC<IRoleEdit> = ({isAdd, user, triggerButton, onSubmit}) => {
  const {loadDictData, loading} = useModel('dict');
  return (
    <ModalForm
      title={isAdd ? '新增用户' : '编辑用户'}
      initialValues={user}
      onFinish={async (values: API.CurrentUser) => {
        await onSubmit?.(values);
        return true;
      }}
      autoFocusFirstInput
      trigger={triggerButton ? triggerButton : isAdd ? <Button type="primary" icon={<DiffOutlined/>}> 新增用户</Button>
        : <Button icon={<EditOutlined/>}> 编辑用户</Button>}
      modalProps={{destroyOnClose: true}}
    >
      <Row gutter={20}>
        <Col span={12}>
          <ProFormText
            disabled={!isAdd}
            name="username" label="用户名" placeholder="请输入用户名"
            rules={[{required: true, message: '请输入用户名'}]}/>
        </Col>
        <Col span={12}>
          <ProFormSelect
            name="type" label="用户类型"
            disabled={!isAdd}
            request={async () => {
              return await loadDictData('user-type');
            }}
            rules={[{required: true, message: '请选择用户类型'}]}
          />
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={12}>
          <ProFormText
            name="phone" label="联系方式" placeholder="请输入联系方式"
            rules={[{required: true, message: '请输入联系方式'}, {
              pattern: /^1\d{10}$/,
              message: '请输入正确的手机号码'
            }]}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name="name" label="姓名" placeholder="请输入姓名"
            rules={[{required: true, message: '请输入联系人姓名'}]}
          />
        </Col>
      </Row>
    </ModalForm>
  );
};

export default UserEditModel;
